package com.doudizu.shoesonline.aop;

import com.doudizu.shoesonline.common.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.doudizu.shoesonline.constant.UserConstant.USER_LOGIN;

/**
 * @author HelloCode
 * @blog https://www.hellocode.top
 * @date 2023年01月11日 17:27
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判断是否需要拦截
        // 1.判断是否需要拦截（ThreadLocal中是否有用户）
        System.out.println("==============拦截器:"+request.getRequestURL());
        String token = request.getHeader("Authorization");

        if (token != null) {
            String id = redisTemplate.opsForValue().get(USER_LOGIN + token);
            UserContext.setUserId(Long.valueOf(id));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUserId();
    }

}
